package com.lancer.chinamobile;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;

/**
 * @author XuJD
 * @create 2019-01-21 17:21
 **/
public class HttpsUtil {


    public static void main(String[] args){

        /**
         * page.currentPage: 1
         * page.perPageSize: 20
         * noticeBean.sourceCH:
         * noticeBean.source:
         * noticeBean.title:
         * noticeBean.startDate:
         */


        Map<String, String> params = new HashMap<String, String>();
        params.put("page.currentPage", "1");
        params.put("page.perPageSize", "20");
        params.put("noticeBean.sourceCH", "");
        params.put("noticeBean.source", "");
        params.put("noticeBean.title", "");
        params.put("noticeBean.startDate", "");


        String s= httpsRequest("https://b2b.10086.cn/b2b/main/listVendorNoticeResult.html?noticeBean.noticeType=2","POST",null);



        System.out.println(s);
    }



    /*
     * 处理https GET/POST请求
     * 请求地址、请求方法、参数
     * */
    public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
        StringBuffer buffer=null;
        try{
            //创建SSLContext
            SSLContext sslContext=SSLContext.getInstance("SSL");
            TrustManager[] tm={new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());;
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf=sslContext.getSocketFactory();
            URL url=new URL(requestUrl);
            HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            //往服务器端写内容
            if(null!=outputStr){
                OutputStream os=conn.getOutputStream();
                os.writeBytes(param);
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is=conn.getInputStream();
            InputStreamReader isr=new InputStreamReader(is,"utf-8");
            BufferedReader br=new BufferedReader(isr);
            buffer=new StringBuffer();
            String line=null;
            while((line=br.readLine())!=null){
                buffer.append(line);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }
}